<template>
  <el-form :inline="true" :model="categoryForm">
    <el-form-item label="一级分类">
      <!--show是父组件传来的值,代表true或false,true的时候为disabled，禁用状态-->
      <el-select placeholder="请选择" v-model="categoryForm.category1Id" @change="handlerChange1" :disabled="show">
        <el-option :label="c1.name" :value="c1.id" v-for="c1 in list1" :key="c1.id"/>
      </el-select>
    </el-form-item>
    <el-form-item label="二级分类">
      <el-select placeholder="请选择" v-model="categoryForm.category2Id" @change="handlerChange2" :disabled="show">
        <el-option :label="c2.name" :value="c2.id" v-for="c2 in list2" :key="c2.id"/>
      </el-select>
    </el-form-item>
    <el-form-item label="三级分类">
      <el-select placeholder="请选择" v-model="categoryForm.category3Id" @change="handlerChange3" :disabled="show">
        <el-option :label="c3.name" :value="c3.id" v-for="c3 in list3" :key="c3.id"/>
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script>
import {reqCategory1List, reqCategory2List, reqCategory3List} from "../api/realRequests";

export default {
  name: "CategorySelect",
  props: ['show'],
  data() {
    return {
      // 一级分类的数据
      list1: [],
      // 二级分类的数据
      list2: [],
      // 三级分类的数据
      list3: [],
      // 收集一级，二级，三级分类的id
      categoryForm: {
        category1Id: '',
        category2Id: '',
        category3Id: ''
      }
    }
  },
  methods: {
    // 获取一级分类的数据
    async getCategory1List() {
      let result = await reqCategory1List();
      // console.log(result)
      if (result.code == 200) {
        this.list1 = result.data
      }
    },
    // 一级分类下拉框选择的数据改变时的回调
    async handlerChange1() {
      // 清除二级，三级分类的数据
      this.list2 = []
      this.list3 = []
      // 清除二级，三级联动下拉框的数据
      this.categoryForm.category2Id = ''
      this.categoryForm.category3Id = ''
      // 解构出一级分类的id
      const {category1Id} = this.categoryForm
      let result = await reqCategory2List(category1Id)
      // console.log(result)
      if (result.code == 200) {
        this.list2 = result.data
      }
    },
    // 三级分类下拉框选择的数据改变时的回调
    async handlerChange2() {
      // 清除三级联动下拉框的数据
      this.categoryForm.category3Id = ''
      const {category2Id} = this.categoryForm
      let result = await reqCategory3List(category2Id)
      // console.log(result)
      if (result.code == 200) {
        this.list3 = result.data
      }
    },
    // 三级分类下拉框选择的数据改变时,给父组件传值，并触发父组件的回调
    handlerChange3() {
      this.$emit('doChange', this.categoryForm)
    }
  },
  mounted() {
    // 挂载后立刻获取一级分类的值
    this.getCategory1List()
  }
}
</script>

<style scoped>

</style>